<script setup name="coupon">
import { computed } from "vue"
import { getCouponList, createCoupon, updateCoupon, deleteCoupon, updateCouponStatus } from "@/api/coupon"
import { useInitTable, useInitForm } from "@/composables/useCommon"
import FormDialog from "@/components/FormDialog.vue"
import ListHeader from "@/components/ListHeader.vue"

const { windowHeight, tableData, loading, currentPage, total, limit, getData, handleDelete, handleStatusChange } = useInitTable({
  getList: getCouponList,
  delete: deleteCoupon,
  updateStatus: updateCouponStatus,
  onGetList: res => {
    tableData.value = res.list.map(v => {
      v.statusText = formatStatus(v)
      return v
    })
    total.value = res.totalCount
  }
})

// 解构表单公共方法
const { form, dialogRef, formRef, rules, dialogTitle, handleSubmit, handleCreate, handleEdit, resetForm } = useInitForm({
  getData,
  updata: updateCoupon,
  create: createCoupon,
  form: {
    name: "",
    type: 0,
    value: 0,
    total: 100,
    min_price: 0,
    start_time: null,
    end_time: null,
    order: 50,
    desc: ""
  },
  rules: {
    name: [{ required: true, message: "优惠券名称不能为空", trigger: "blur" }],
    type: [{ required: true }],
    value: [{ required: true, trigger: "blur" }],
    total: [{ required: true }],
    min_price: [{ required: true }],
    order: [{ required: true }],
    desc: [{ required: true, message: "优惠券描述不能为空", trigger: "blur" }],
    timerange: [{ required: true }]
  },
  beforeSubmit: val => {
    if (typeof val.start_time !== "number") {
      val.start_time = new Date(val.start_time).getTime()
    }
    if (typeof val.end_time !== "number") {
      val.end_time = new Date(val.end_time).getTime()
    }
    return val
  }
})

// 减去头部高度、标签高度、内边距高度
let h = windowHeight.value - 64 - 44 - 36
const h2 = windowHeight.value - 64 - 44 - 110

// 格式化状态
const formatStatus = row => {
  let status = "领取中"
  // 获取开始时间戳
  let start_time = new Date(row.start_time).getTime()
  // 获取当前时间
  let now = new Date().getTime()
  // 获取结束时间戳
  let end_time = new Date(row.end_time).getTime
  if (start_time > now) {
    status = "未开始"
  } else if (end_time < now) {
    start_time = "已结束"
  } else if (row.status === 0) {
    status = "已失效"
  }
  return status
}
const timerange = computed({
  get() {
    return form.start_time && form.end_time ? [form.start_time, form.end_time] : []
  },
  set(val) {
    form.start_time = val[0]
    form.end_time = val[1]
  }
})
</script>

<template>
  <el-card shadow="never" :body-style="{ 'padding-bottom': '10px', 'padding-left': '0', 'padding-right': '0' }"
    :style="{ height: `${h}px` }">
    <ListHeader create="新增优惠券" @create="handleCreate" @refresh="getData" />
    <div class="card-table" :style="{ height: `${h2}px` }">
      <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">
        <el-table-column label="优惠券名称" min-width="160">
          <template #default="{ row }">
            <div class="coupon-name" :class="row.statusText === '领取中' ? 'active' : 'disable'">
              <h5>{{ row.name }}</h5>
              <small>{{ row.start_time }} ~ </small>
              <small>{{ row.end_time }}</small>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="statusText" label="状态" />
        <el-table-column label="优惠" min-width="120">
          <template #default="{ row }"> {{ row.type === 0 ? "满减" : "折扣" }} {{ row.type === 0 ? `￥${row.value}` :
            `${row.value} 折` }} </template>
        </el-table-column>
        <el-table-column prop="total" label="发放数量" align="center" />
        <el-table-column prop="used" label="已使用" align="center" />
        <el-table-column label="操作" width="116" align="center">
          <template #default="{ row }">
            <div class="row-action">
              <el-tooltip v-if="row.statusText === '未开始'" effect="light" content="修改" placement="left">
                <el-icon :size="15" @click="handleEdit(row)">
                  <View />
                </el-icon>
              </el-tooltip>

              <el-popconfirm v-if="row.statusText !== '领取中'" width="190" title="是否要删除该优惠券？" confirmButtonText="确认"
                cancelButtonText="取消" @confirm="handleDelete(row.id)">
                <template #reference>
                  <el-icon :size="15">
                    <CloseBold />
                  </el-icon>
                </template>
              </el-popconfirm>

              <el-popconfirm v-if="row.statusText === '领取中'" width="200" title="是否要将该优惠券失效？" confirmButtonText="失效"
                cancelButtonText="取消" @confirm="handleStatusChange(0, row)">
                <template #reference>
                  <el-icon :size="15">
                    <Failed />
                  </el-icon>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据" :image-size="200" />
        </template>
      </el-table>

      <div class="coupon-pagination">
        <el-pagination background small layout="prev, pager, next" :total="total" :current-page="currentPage"
          :page-size="limit" :hide-on-single-page="total < 11" @current-change="getData" />
      </div>
    </div>

    <FormDialog ref="dialogRef" :width="60" :title="dialogTitle" @submit="handleSubmit" @close="resetForm">
      <el-form :model="form" ref="formRef" :rules="rules" :inline="false" label-width="94">
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="0">满减</el-radio>
            <el-radio :label="1">折扣</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优惠券面值" prop="value">
          <el-input class="price" v-model="form.value" placeholder="面值">
            <template #append>{{ form.type ? "折" : "元" }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="发行量" prop="type">
          <el-input-number v-model="form.total" :min="0" :max="10000" />
        </el-form-item>
        <el-form-item label="最低使用价" prop="min_price">
          <el-input class="price" v-model="form.min_price" placeholder="请输入最低使用价">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="优惠券排序" prop="order">
          <el-input-number v-model="form.order" :min="0" :max="1000" />
        </el-form-item>
        <el-form-item label="活动时间">
          <el-date-picker v-model="timerange" :editable="false" value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange"
            range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item>
        <el-form-item label="优惠券描述" prop="desc">
          <el-input v-model="form.desc" placeholder="描述" type="textarea" :rows="5" resize="none" />
        </el-form-item>
      </el-form>
    </FormDialog>
  </el-card>
</template>

<style lang="scss" scoped>
.el-card {
  border: 0;
  overflow-y: auto;

  .coupon-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
    padding: 0 20px;

    .el-icon:first-child {
      color: var(--white);
    }
  }

  .card-table {
    display: flex;
    justify-content: space-between;
    flex-direction: column;

    .el-table {
      z-index: 0;

      .coupon-name {
        border: 1px dashed #e1e3e8;
        padding: 4px;
        border-radius: 4px;

        h5 {
          font-weight: bold;
          font-size: 14px;
        }
      }

      .row-action {
        .el-icon {
          cursor: pointer;
          margin: 0 6px;

          &:last-child {
            margin-right: 0;
          }
        }
      }
    }

    .coupon-pagination {
      display: flex;
      justify-content: center;
      padding-top: 10px;
    }
  }

  .el-dialog {
    .price {
      width: 42.4%;
    }
  }

  .active {
    border: var(--activeBorder);
    background: var(--activeBg);
    color: var(--activeColor);
  }

  .disable {
    border: var(--disableBorder);
    background: var(--disableBg);
    color: var(--disableColor);
  }
}

@media screen and (max-width: 375px),
screen and (max-width: 414px) {
  :deep(.el-dialog--center) {
    min-width: 70% !important;
    max-width: 70% !important;
  }
}</style>
